<template>
  <div class="alarmConfiguration zy-content">
    <div class="searchBox search-box-layout">
      <Row :gutter="24">
        <Col span="4">
          <div>
            <p class="label">异常类型名称</p>
            <div class="ipt">
              <Input
                type="text"
                v-model="searchParams.shutdownCategory"
                clearable
                :placeholder="`${$t('common.inputInfo')}`"
                :maxlength="32"
              ></Input>
            </div>
          </div>
        </Col>
        <Col span="4">
          <div>
            <p class="label hide-label">--</p>
            <div class="ipt">
              <Button
                class="search-btn"
                type="primary"
                @click="changeNum()"
              >{{ $t('common.Query') }}</Button>
              <Button class="reset-btn" @click="reset()">{{ $t('common.reset') }}</Button>
            </div>
          </div>
        </Col>
      </Row>
    </div>
    <Row :gutter="24">
      <Col span="12">
        <div class="list-layout mt16">
          <div class="btns clear">
            <span class="title">停机类别</span>
            <Button @click="createtype('add', {})">{{ $t('common.New') }}</Button>
          </div>
          <div class="tableContent">
            <Table
              class="resizable-table"
              highlight-row
              @on-row-click="rowClick"
              border
              @on-column-width-resize="onColumnWidthResize"
              :columns="columnsList"
              ellipsis
              ref="selection"
              stripe
              :data="dataArr"
              @on-selection-change="onSelectChange"
            >
              <template slot-scope="{ row }" slot="action">
                <span class="operationBtn" @click="createtype('edit', row)">
                  <i class="iconfont zy-common-bianji"></i>
                  {{
                  $t('common.Edit') }}
                </span>
                <span class="operationBtn" @click="delPrrShowH(row, 'type')">
                  <i class="iconfont zy-common-shanchu"></i>
                  {{
                  $t('common.Delete') }}
                </span>
              </template>
            </Table>
          </div>
          <!-- 分页 -->
          <div class="pageWrap mt16">
            <pageLeftTitle :total="total" :selected="delIds.length" />
            <Page
              :total="total"
              :page-size="pageSize"
              :page-size-opts="pageSizeOption"
              :current="pageNum"
              @on-change="changePageNum"
              @on-page-size-change="changePageSize"
              show-sizer
              show-total
            />
          </div>
        </div>
      </Col>

      <Col span="12">
        <div class="list-layout mt16">
          <div class="btns clear">
            <span class="title">停机原因</span>
            <Button @click="createfaultCodeShowH2">{{ $t('common.New') }}</Button>
            <Button @click="exportTemplateClick">{{ $t('common.batchExport') }}</Button>
            <Button @click="importExcelShow">{{ $t('common.Import') }}</Button>
            <Button @click="exportTemplate">{{ $t('common.Download') }}</Button>
          </div>
          <!-- 表格 -->
          <div class="tableContent">
            <Table
              class="resizable-table"
              border
              @on-column-width-resize="(a,b,c,d)=>{onColumnWidthResize(a,b,c,d,'exception')}"
              :columns="columns2"
              ellipsis
              ref="selection1"
              stripe
              :data="dataArr2"
              @on-selection-change="onSelectChange2"
            >
              <template slot-scope="{ row }" slot="action">
                <span class="operationBtn" @click="createfaultCodeShowH2(row)">
                  <i class="iconfont zy-common-bianji"></i>
                  {{
                  $t('common.Edit') }}
                </span>
                <span class="operationBtn" @click="delPrrShowH(row, 'result')">
                  <i class="iconfont zy-common-shanchu"></i>
                  {{
                  $t('common.Delete') }}
                </span>
              </template>
            </Table>
          </div>
          <!-- 分页 -->
          <div class="pageWrap mt16">
            <pageLeftTitle :total="total2" :selected="delIds2.length" />
            <Page
              :total="total2"
              :page-size="pageSize2"
              :page-size-opts="pageSizeOption"
              :current="pageNum2"
              @on-change="changePageNum2"
              @on-page-size-change="changePageSize2"
              show-sizer
              show-total
            />
          </div>
        </div>
      </Col>
    </Row>

    <!-- 新增编辑停机类别 -->
    <Modal :mask-closable="false" v-model="create" :title="addtitle" class="modal-content-layout">
      <Form
        ref="form"
        class="formList"
        :model="formItem"
        label-position="top"
        :rules="ruleValidate"
      >
        <FormItem label="停机类别" prop="shutdownCategory">
          <Input
            type="text"
            v-model="formItem.shutdownCategory"
            :placeholder="`${$t('common.inputInfo')}`"
            :maxlength="32"
          ></Input>
        </FormItem>
        <FormItem label="备注" prop="remarks">
          <Input
            type="textarea"
            v-model="formItem.remarks"
            :placeholder="`${$t('common.inputInfo')}`"
            :maxlength="32"
          ></Input>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="default" @click="create = false">{{ $t('common.Cancle') }}</Button>
        <Button
          type="primary"
          :loading="loading"
          @click="addOk('form')"
        >{{ $t('maintenance.Confirmed') }}</Button>
      </div>
    </Modal>
    <!-- 停机原因新增编辑 -->
    <Modal
      :mask-closable="false"
      v-model="createRes"
      :title="addtitle"
      class="modal-content-layout"
    >
      <Form
        ref="formRes"
        class="formList"
        :model="formItemRes"
        label-position="top"
        :rules="ruleValidateRes"
      >
        <FormItem label="停机原因" prop="reasonForShutdown">
          <Input
            type="text"
            v-model="formItemRes.reasonForShutdown"
            :placeholder="`${$t('common.inputInfo')}`"
            :maxlength="32"
          ></Input>
        </FormItem>
        <FormItem label="维修单类型" prop="repairOrderType">
          <Select v-model="formItemRes.repairOrderType" :placeholder="`${$t('common.selectInfo')}`">
            <Option
              v-for="(item) of repairList"
              :value="item.value"
              :key="item.index"
              :label="item.value"
            ></Option>
          </Select>
        </FormItem>
        <FormItem label="是否计划停机" prop="unplannedStandby">
          <Select
            v-model="formItemRes.unplannedStandby"
            :placeholder="`${$t('common.selectInfo')}`"
          >
            <Option value="是" label="是"></Option>
            <Option value="否" label="否"></Option>
          </Select>
        </FormItem>
        <FormItem :label="$t('common.remarks')" prop="remarks">
          <Input
            type="textarea"
            v-model="formItemRes.remarks"
            :placeholder="`${$t('common.inputInfo')}`"
            :autosize="{ minRows: 2, maxRows: 5 }"
          ></Input>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="default" @click="createRes = false">{{ $t('common.Cancle') }}</Button>
        <Button type="primary" :loading="loading" @click="addOk2('formRes')">
          {{ $t('maintenance.Confirmed')
          }}
        </Button>
      </div>
    </Modal>
    <!-- 请确认是否删除弹框 -->
    <Modal
      :mask-closable="false"
      v-model="delFaultCodeShowF"
      :title="$t('common.Delete')"
      class="modal-title-layout"
    >
      <div class="icon red">
        <i class="iconfont zy-common-shanchu"></i>
      </div>
      <p class="title">
        <span>{{ $t('common.confirmDelete') }}</span>
      </p>
      <div slot="footer">
        <Button type="default" @click="delFaultCodeShowF = false">{{ $t('common.Cancle') }}</Button>
        <Button
          type="primary"
          :loading="loading"
          @click="deleteOk"
        >{{ $t('maintenance.Confirmed') }}</Button>
      </div>
    </Modal>

    <importExcelModal
      :importExcelStateF="importExcelState"
      url="/dms/shutdownReason/import"
      v-if="importExcelState"
      @importExcelChange="importExcelChange"
    ></importExcelModal>
  </div>
</template>

<script>
import fileDownload from "js-file-download";
import toggleTableOperation from "@/mixins/toggleTableOperation";
import importExcelModal from "@/components/importExcelNew.vue";
export default {
  name: "exception",
  components: { importExcelModal },
  mixins: [toggleTableOperation],
  data() {
    return {
      shelfList: [],
      locationList: [],
      importExcelState: false /*批量导入*/,
      formItem: {},
      formItemRes: {},
      addtitle: "",
      allCheck: false,
      loading: false,
      create: false,
      searchParams: {},
      pageNum: 1,
      pageSize: 10,
      total: 0,

      repairList: [
        {
          value: "否"
        },
        {
          value: "设备故障"
        },
        {
          value: "模具故障"
        }
      ],
      pageNum2: 1,
      pageSize2: 10,
      total2: 0,

      createRes: false,
      columns: [
        {
          title: "停机类别",
          key: "shutdownCategory",
          width: 100,
          align: "center",
          resizable: true
        },

        {
          title: "备注",
          key: "remarks",
          width: 100,
          align: "center",
          resizable: true
        },
        {
          title: "维护人",
          key: "operator",
          width: 100,
          align: "center",
          resizable: true
        },
        {
          title: "维护时间",
          key: "maintenanceTime",
          width: 100,
          align: "center",
          resizable: true
        },
        {
          title: "操作",
          slot: "action",
          fixed: "right",
          width: 180,
          align: "center"
        }
      ],
      columns2: [
        {
          title: "停机原因",
          key: "reasonForShutdown",
          width: 150,
          align: "center",
          resizable: true
        },
        {
          title: "维修单类型",
          key: "repairOrderType",
          width: 150,
          align: "center",
          resizable: true
        },
        {
          title: "是否计划外待机",
          key: "unplannedStandby",
          width: 200,
          align: "center",
          resizable: true
        },
        {
          title: "备注",
          key: "remarks",
          width: 100,
          align: "center",
          resizable: true
        },
        {
          title: "维护时间",
          key: "maintenanceTime",
          width: 100,
          align: "center",
          resizable: true
        },
        {
          title: "维护人",
          key: "operator",
          width: 100,
          align: "center",
          resizable: true
        },
        {
          title: "操作",
          slot: "action",
          fixed: "right",
          width: 180,
          align: "center"
        }
      ],
      dataArr: [],
      dataArr2: [],
      delFaultCodeShowF: false, //是否显示删除弹窗
      pageSizeOption: [10, 20, 30, 40],
      delIds: [],
      delIds2: [],
      selection: [],
      checkBtnPermission: {},
      ruleValidate: {
        shutdownCategory: [
          { required: true, message: "请填写停机类别", trigger: "blur" }
        ]
      },
      ruleValidateRes: {
        reasonForShutdown: [
          { required: true, message: "请填写停机原因", trigger: "blur" }
        ],
        repairOrderType: [
          { required: true, message: "请选择", trigger: "blur" }
        ],
        unplannedStandby: [
          { required: true, message: "请选择", trigger: "blur" }
        ]
      },
      rows: {},
      type: ""
    };
  },
  mounted() {
    this.getTableColumnsWidth(this.columns);
    this.getTableColumnsWidth(this.columns2, "exception");
    this.searchList();
  },
  methods: {
    reset() {
      this.searchParams = {};
      this.changeNum();
    },
    //分页
    changeNum() {
      this.pageNum = 1;
      this.searchList();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.searchList();
    },

    changePageNum(val) {
      this.pageNum = val;
      this.searchList();
    },
    changeNum2() {
      this.pageNum2 = 1;
      this.searchList();
    },
    changePageSize2(pageSize) {
      this.pageSize2 = pageSize;
      this.searchList2();
    },
    changePageNum2(val) {
      this.pageNum2 = val;
      this.searchList2();
    },
    //查询列表
    searchList() {
      let params = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        ...this.searchParams
      };
      this.axios({
        method: "GET",
        url: "/dms/shutdownCategory/getShutdownCategoryList",
        params: params
      }).then(res => {
        if (res.code === 200) {
          this.dataArr = res.data.records;
          this.total = res.data.total;
        } else {
          this.$Message.warning({
            content: res.msg,
            duration: 6,
            closable: true
          });
        }
      });
    },
    searchList2() {
      let params = {
        pageNum: this.pageNum2,
        pageSize: this.pageSize2,
        abnormalId: this.rows.id
      };
      this.axios({
        method: "GET",
        url: "/dms/shutdownReason/getShutdownReasonList",
        params
      }).then(res => {
        if (res.code === 200) {
          this.dataArr2 = res.data.records;
          this.total2 = res.data.total;
        } else {
          this.$Message.warning({
            content: res.msg,
            duration: 6,
            closable: true
          });
        }
      });
    },
    //增加或编辑
    createtype(type, row) {
      this.$refs.form.resetFields();
      if (row.id) {
        this.addtitle = `${this.$t("common.Edit")}`;
        this.formItem = {
          ...row
        };
      } else {
        this.addtitle = `${this.$t("common.New")}`;
        this.formItem = {
          shutdownCategory: "",
          remarks: ""
        };
      }
      this.create = true;
    },
    rowClick(row) {
      this.rows = row;
      this.searchList2();
    },
    //增加或编辑
    createfaultCodeShowH2(row) {
      if (!this.rows.id) {
        this.$Message.warning({
          content: "请选择一条停机类别",
          duration: 6,
          closable: true
        });
        return;
      }
      this.$refs.form.resetFields();
      if (row.id) {
        this.addtitle = `${this.$t("common.Edit")}`;
        this.formItemRes = {
          ...row
        };
      } else {
        this.addtitle = `${this.$t("common.New")}`;
        this.formItemRes = {};
      }
      this.createRes = true;
    },
    addOk(name) {
      this.$refs[name].validate(valid => {
        if (!valid) {
          return;
        } else {
          this.loading = true;
          if (this.formItem.id) {
            this.axios({
              url: `/dms/shutdownCategory/updateShutdownCategory`,
              method: "POST",
              data: this.formItem
            }).then(res => {
              this.loading = false;
              0;
              if (res.code === 200) {
                this.changeNum();
                this.$Message.success("编辑成功");
                this.create = false;
              } else {
                this.$Message.warning({
                  content: res.msg,
                  duration: 6,
                  closable: true
                });
              }
            });
          } else {
            this.axios({
              url: `/dms/shutdownCategory/addShutdownCategory`,
              method: "post",
              data: this.formItem
            }).then(res => {
              this.loading = false;
              if (res.code === 200) {
                this.changeNum();
                this.$Message.success("新增成功");
                this.create = false;
              } else {
                this.$Message.warning({
                  content: res.msg,
                  duration: 6,
                  closable: true
                });
              }
            });
          }
        }
      });
    },
    addOk2(name) {
      this.$refs[name].validate(valid => {
        if (!valid) {
          return;
        } else {
          this.loading = true;
          if (this.formItemRes.id) {
            this.axios({
              url: `/dms/shutdownReason/updateShutdownReason`,
              method: "POST",
              data: {
                ...this.formItemRes,
                abnormalId: this.rows.id
              }
            }).then(res => {
              this.loading = false;
              if (res.code === 200) {
                this.searchList2();
                this.$Message.success("编辑成功");
                this.createRes = false;
              } else {
                this.$Message.warning({
                  content: res.msg,
                  duration: 6,
                  closable: true
                });
              }
            });
          } else {
            this.axios({
              url: `/dms/shutdownReason/addShutdownReason`,
              method: "post",
              data: {
                ...this.formItemRes,
                abnormalId: this.rows.id
              }
            }).then(res => {
              this.loading = false;
              if (res.code === 200) {
                this.searchList2();
                this.$Message.success("新增成功");
                this.createRes = false;
              } else {
                this.$Message.warning({
                  content: res.msg,
                  duration: 6,
                  closable: true
                });
              }
            });
          }
        }
      });
    },
    //勾选列表
    onSelectChange(selection) {
      let myArray = [];
      selection.map((item, index) => {
        myArray.push(item.id);
      });
      this.delIds = myArray;
      if (selection.length > 0) {
        this.allCheck = true;
      } else {
        this.allCheck = false;
      }
    },
    //批量删除
    delFaultCodeShowClick() {
      if (this.delIds.length == 0) {
        this.$Message.warning({
          content: `${this.$t("common.deleteItems")}`,
          duration: 6,
          closable: true
        });
        return;
      } else {
        this.delFaultCodeShowF = true;
      }
    },
    //删除
    delPrrShowH(row, type) {
      this.type = type;
      //点击展示提示删除弹窗
      this.delFaultCodeShowF = true;
      this.delIds = [];
      this.delIds.push(row.id);
    },
    deleteOk() {
      this.loading = true;
      // let params = { delIds: this.delIds }
      this.axios({
        url:
          this.type == "type"
            ? "/dms/shutdownCategory/deleteById"
            : "/dms/shutdownReason/deleteById",
        method: "DELETE",
        data: this.delIds
      }).then(res => {
        this.loading = false;
        if (res.code === 200) {
          if (this.type == "type") {
            this.searchList();
          } else {
            this.searchList();
            this.searchList2();
          }
          this.$Message.success("删除成功");
          this.delFaultCodeShowF = false;
        } else {
          this.$Message.warning({
            content: res.msg,
            duration: 6,
            closable: true
          });
        }
      });
    },
    //下载模板
    exportTemplate() {
      const filName = "异常定义导入模板";
      this.axios({
        url: "/dms/shutdownReason/shutdownReasonTemplate",
        method: "GET",
        responseType: "blob"
      }).then(res => {
        fileDownload(res, filName + ".xlsx");
      });
    },
    //导入
    importExcelShow() {
      // if (!this.rows.id) {
      //     this.$Message.warning(({ content: '请选择一条停机类别', duration: 6, closable: true }));
      //     return
      // }
      this.importExcelState = true;
    },
    importExcelChange(val) {
      this.importExcelState = false;
      if (val === "success") {
        this.changeNum();
      }
    },
    //导出
    exportTemplateClick() {
      // let params = {};
      // for (let key in this.searchParams) {
      //     if (this.searchParams[key]) {
      //         this.$set(params, key, this.searchParams[key])
      //     }
      // }
      const filName = "异常定义";
      this.axios({
        url: "/dms/shutdownReason/export",
        method: "POST",
        // data: params,
        responseType: "blob"
      }).then(res => {
        fileDownload(res, filName + ".xls");
      });
    }
  }
};
</script>

<style scoped lang="scss">
.ivu-input-number {
  width: -webkit-fill-available;
}

.row_click {
  cursor: pointer;
  color: rgb(50, 113, 240) !important;
}
</style>